package com.vietnam.power.admin.controller;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.collections.CollectionUtils;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.MessageSource;
import org.springframework.context.i18n.LocaleContextHolder;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import com.vietnam.power.constant.GeneralConstant;
import com.vietnam.power.domain.Article;
import com.vietnam.power.domain.ArticleGroup;
import com.vietnam.power.domain.ArticleSearchCriteria;
import com.vietnam.power.service.ArticleService;
import com.vietnam.power.service.FileService;

@Controller(value = "adminNewsController")
@RequestMapping("/admin")
public class NewsController {
	private static Logger logger = Logger.getLogger(NewsController.class);
	@Autowired
	private MessageSource messageSource;

	@Autowired
	private ArticleService articleService;

	@Autowired
	private FileService fileService;

	@RequestMapping(value = { "/saveArticle" }, method = RequestMethod.POST)
	public String saveArticle(HttpServletRequest request, HttpServletResponse response, @ModelAttribute(value = "article") Article article) {

		logger.debug(article.getId());
		if (article.getId() == null) {
			articleService.createArticle(article);
		} else if (article.getId() != null) {
			List<Integer> fileIds = articleService.updateArticle(article);
			if (CollectionUtils.isNotEmpty(fileIds)) {
				for (Integer i : fileIds) {
					fileService.deleteFile(i, request.getSession().getServletContext().getRealPath("/"));
				}
			}
		}

		return "redirect:/admin/viewArticle.html?id=" + article.getId();
	}

	@RequestMapping(value = { "/createArticle" }, method = RequestMethod.GET)
	public ModelAndView createArticle(HttpServletRequest request, HttpServletResponse response) {
		ModelAndView mav = new ModelAndView("admin/selectArticleGroup");

		mav.addObject("articleGroups", buildArticleGroupList());
		mav.addObject("article", new Article());
		mav.addObject("pageTitle", messageSource.getMessage("admin.article.title", null, LocaleContextHolder.getLocale()));
		return mav;
	}

	@RequestMapping(value = { "/createArticle" }, method = RequestMethod.POST)
	public ModelAndView createArticle(HttpServletRequest request, HttpServletResponse response, @ModelAttribute(value = "article") Article article) {
		ModelAndView mav = new ModelAndView("admin/newArticle");
		article.setArticleGroupName(articleService.getArticleGroup(article.getArticelGroupId()).getName());
		mav.addObject("articleGroups", buildArticleGroupList());
		mav.addObject("article", article);
		mav.addObject("pageTitle", messageSource.getMessage("admin.article.title", null, LocaleContextHolder.getLocale()));
		return mav;
	}

	@RequestMapping(value = { "/viewArticle" }, method = RequestMethod.GET)
	public ModelAndView viewArticle(HttpServletRequest request, HttpServletResponse response, @RequestParam(value = "id", required = true) int id) {
		ModelAndView mav = new ModelAndView("admin/newArticle");

		mav.addObject("articleGroups", buildArticleGroupList());
		mav.addObject("article", articleService.getArticleById(id));
		mav.addObject("mode", GeneralConstant.MODE_VIEW);
		mav.addObject("pageTitle", messageSource.getMessage("admin.article.title", null, LocaleContextHolder.getLocale()));
		return mav;
	}

	@RequestMapping(value = { "/updateArticle" }, method = RequestMethod.GET)
	public ModelAndView updateArticle(HttpServletRequest request, HttpServletResponse response, @RequestParam(value = "id", required = true) int id) {
		ModelAndView mav = new ModelAndView("admin/newArticle");
		logger.debug("product group id: " + id);

		mav.addObject("mode", GeneralConstant.MODE_EDIT);
		mav.addObject("articleGroups", buildArticleGroupList());
		mav.addObject("article", articleService.getArticleById(id));
		mav.addObject("pageTitle", messageSource.getMessage("admin.article.title", null, LocaleContextHolder.getLocale()));
		return mav;
	}

	@RequestMapping(value = { "/searchArticle" }, method = RequestMethod.GET)
	public ModelAndView searchArticle(HttpServletRequest request, HttpServletResponse response) {
		ModelAndView mav = new ModelAndView("admin/searchArticle");
		Map<Integer,String> map = buildArticleGroupList();
		map.put(null, messageSource.getMessage("admin.article.group.all", null, LocaleContextHolder.getLocale()));
		
		mav.addObject("searchArticle", new ArticleSearchCriteria());
		mav.addObject("articleGroups", map);
		mav.addObject("pageTitle", messageSource.getMessage("admin.article.title", null, LocaleContextHolder.getLocale()));
		return mav;
	}

	@RequestMapping(value = { "/searchArticle" }, method = RequestMethod.POST)
	public ModelAndView searchArticle(HttpServletRequest request, HttpServletResponse response, @ModelAttribute(value = "searchArticle") ArticleSearchCriteria s) {
		ModelAndView mav = new ModelAndView("admin/searchArticle");
		Map<Integer,String> map = buildArticleGroupList();
		map.put(null, messageSource.getMessage("admin.article.group.all", null, LocaleContextHolder.getLocale()));
		
		mav.addObject("searchArticle", s);
		mav.addObject("articleGroups", map);
		mav.addObject("rs", articleService.searchArticle(s));
		mav.addObject("pageTitle", messageSource.getMessage("admin.article.title", null, LocaleContextHolder.getLocale()));
		return mav;
	}

	@RequestMapping(value = { "/deleteArticle/{id}" }, method = RequestMethod.DELETE)
	public @ResponseBody
	void deleteArticle(HttpServletRequest request, HttpServletResponse response, @PathVariable(value = "id") int id) {
		List<Integer> fileIds = articleService.deleteArticle(id);
		for (Integer i : fileIds) {
			fileService.deleteFile(i, request.getSession().getServletContext().getRealPath("/"));
		}
	}

	@RequestMapping(value = { "/validateArticleGroup" }, method = RequestMethod.POST)
	public @ResponseBody
	String validateArticleGroup(@RequestParam(value = "id") int id) {

		if (articleService.validateArticlesInGroup(id)) {
			return "success";
		}

		return "failed";
	}
	
	private Map<Integer,String> buildArticleGroupList() {
		Map<Integer,String> articleGroupList = new HashMap<Integer, String>();
		for (ArticleGroup ag : articleService.getArticleGroupList()) {

			articleGroupList.put(ag.getId(), messageSource.getMessage(ag.getDescription(), null, LocaleContextHolder.getLocale()));
		}
		
		return articleGroupList;
	}
}
